# To add a new cell, type '# %%'
# To add a new markdown cell, type '# %% [markdown]'
# %%
from IPython import get_ipython

# %% [markdown]
# ## 导入相关库
# >"os:关闭tensorflow的分离提示"
# >"util.utils_cv：程序中会用到的图像处理工具"
# >"utils.grab：机械臂抓取辅助"
# >"utils.keys_prov:存储省份信息的字典"
# >"angle_detect:分析文字方向"
# >

# %%
import os
import tensorflow as tf
import cv2 as cv
import numpy as np

from util.utils_cv import test_imshow,find_box,crop_rotate_box,rotate_img
from util.grab import *
from util.keys_prov import *
from util.utils_recg import *
from angle.predict import predict as angle_detect
from ctpn.text_detect import text_detect

import matplotlib.pyplot as plt

os.environ['TF_CPP_MIN_LOG_LEVEL'] = '3'

# %matplotlib inline
# get_ipython().run_line_magic('matplotlib', 'inline')
plt.rcParams['figure.figsize'] = (16.0,9.0) # set default size of plots
plt.rcParams['figure.dpi']=300
# plt.rcParams['image.interpolation'] = 'nearest'
plt.rcParams['image.cmap'] = 'gray'

origin_img = cv.imread("./img/1153_Rotated.jpg")


# %%
def crnnRec(im, text_recs, ocrMode='keras', adjust=False):
    """
    crnn模型，ocr识别
    @@model,
    @@converter,
    @@im:Array
    @@text_recs:text box

    """
    index = 0
    results = {}
    xDim, yDim = im.shape[1], im.shape[0]

    for index, rec in enumerate(text_recs):
        results[index] = [
            rec,
        ]
        xlength = int((rec[6] - rec[0]) * 0.1)
        ylength = int((rec[7] - rec[1]) * 0.2)
        if adjust:
            pt1 = (max(1, rec[0] - xlength), max(1, rec[1] - ylength))
            pt2 = (rec[2], rec[3])
            pt3 = (min(rec[6] + xlength, xDim - 2),
                   min(yDim - 2, rec[7] + ylength))
            pt4 = (rec[4], rec[5])
        else:
            pt1 = (max(1, rec[0]), max(1, rec[1]))
            pt2 = (rec[2], rec[3])
            pt3 = (min(rec[6], xDim - 2), min(yDim - 2, rec[7]))
            pt4 = (rec[4], rec[5])

        degree = degrees(atan2(pt2[1] - pt1[1], pt2[0] - pt1[0]))  ##图像倾斜角度

        partImg = dumpRotateImage(im, degree, pt1, pt2, pt3, pt4)
        # 根据ctpn进行识别出的文字区域，进行不同文字区域的crnn识别
        image = Image.fromarray(partImg).convert('L')
        # 进行识别出的文字识别
        if ocrMode == 'keras':
            sim_pred = ocr(image)
        else:
            sim_pred = crnnOcr(image)

        results[index].append(sim_pred)  ##识别文字

    return results

# %% [markdown]
# ### 图像预处理

# %%
gray_img = cv.cvtColor(origin_img, cv.COLOR_BGR2GRAY)
blur_img = cv.GaussianBlur(gray_img, (7, 7), 1)
_, thresh_img = cv.threshold(
    blur_img, 0, 255, cv.THRESH_BINARY+cv.THRESH_OTSU)
# test_imshow(thresh_img, cv_show=False)

blur_img = cv.medianBlur(thresh_img,13)
# test_imshow(blur_img, cv_show=False)

# %% [markdown]
# ### 识别标签边框

# %%
img,contours,_= cv.findContours(blur_img, cv.RETR_LIST, cv.CHAIN_APPROX_SIMPLE)
contours = contours[::-1]
test_img = origin_img.copy()
labels=[]
boxes = find_box(contours)
move(boxes)
for box in boxes:
    cv.drawContours(test_img,[box],0,(0,0,255),3)
    labels.append(crop_rotate_box(box,origin_img))
# test_imshow(test_img, cv_show=False)

# %% [markdown]
# ### 标签旋转、裁减与文字标定

# %%

for label in labels:

    if angle_detect(img=label)==180:
        label = rotate_img(label)
    # test_imshow(label,cv_show=False)
    y1=(int)(0.15*len(label[0][:]))
    y2=(int)(0.36*len(label[0][:]))
    label = label[:][y1:y2][:]
    # test_imshow(label,cv_show=False)
    text_recs,temp,img = text_detect(label)
    # test_imshow(temp,cv_show=False)
    text_recs = sort_box(text_recs)
    print(text_detect)
    result = crnnRec(img,text_recs,ocrMode='other',adjust=True)
    print(result)


# %%
print(str(province.keys()))
print(str(province.values()))


# %%



